package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userDao;
    @Autowired
    private RoleMapper roleDao;
    /*@Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
*/
    @Override
    /*根据姓名查询*/
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    /*带条件分页查询*/
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<User> User = userDao.findByCondition(queryString);
        long total = User.getTotal();
        List<com.itheima.pojo.User> result = User.getResult();
        return new PageResult(total, result);
    }

    /*根据id查询用户*/
    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }

    /*修改*/
    @Override
    public void edit(User user, Integer[] roleIds) {

        userDao.edit(user);
        roleDao.detele(user.getId());
        setUserAndRole(user.getId(),roleIds);

    }

    @Override
    public void userAdd(User user, Integer[] roleIds) {
        //String pwd = MD5Utils.md5(user.getPassword());
        //String pwd = bCryptPasswordEncoder.encode(user.getPassword());
        //user.setPassword(pwd);
        userDao.userAdd(user);

        setUserAndRole(user.getId(),roleIds);

    }

    @Override
    public void delete(Integer id) {
        roleDao.detele(id);
        userDao.delete(id);
    }

    @Override
    public List<Integer> findrolesByUserId(Integer id) {
        return userDao.findrolesByUserId(id);
    }

    public void setUserAndRole(Integer userId,Integer[] roleIds){
        //设置多对多关系
        if(roleIds != null && roleIds.length > 0){
            for (Integer roleId : roleIds) {//检查项id
                roleDao.setUserAndRole(userId,roleId);
            }
        }
    }


    //获取所有的健康管理师用户
    @Override
    public List<User> findAllHeathUser() {
        return userDao.findAllHeathUser();
    }
}
